﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.ForeignKey;
using Reporting.Domain.ForeignKey;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.Invoicetypes;

namespace Reporting.API.Application.CommandHandler.ForeignKey
{
    /// <summary>
    /// 发票类型
    /// </summary>
    public class InvoicetypeCommondHandler : IRequestHandler<InvoicetypeCommond, ApiResult<IList<Invoicetype>>>
    {
        private readonly IInvoicetypeRepository _invoicetypeRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<InvoicetypeCommondHandler> _logger;

        public InvoicetypeCommondHandler(ILogger<InvoicetypeCommondHandler> logger, IMapper mapper, IInvoicetypeRepository invoicetypeRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _invoicetypeRepository = invoicetypeRepository;
        }

        public async Task<ApiResult<IList<Invoicetype>>> Handle(InvoicetypeCommond request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有
                var Invoicetypes = await _invoicetypeRepository.GetAllAsync();

                var result = _mapper.Map<IList<Invoicetype>>(Invoicetypes);

                // 返回成功结果
                return ApiResult<IList<Invoicetype>>.Success(result, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {

                // 返回失败结果
                return ApiResult<IList<Invoicetype>>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }
    }
}
